# -*- coding: utf-8 -*-
# @Time    : 2019/10/22 11:23
# @Author  : 岳保保
# @File    : CorsMiddleWare.py
# @Software: PyCharm
from django.core.exceptions import ObjectDoesNotExist
from django.utils.deprecation import MiddlewareMixin

from utils.middleware.CustomException import CustomException


class CorsMiddleWare(MiddlewareMixin):

    @staticmethod
    def process_response(request, response):
        if request.method == "OPTIONS":
            response["Access-Control-Allow-Methods"] = "GET,POST,DELETE,PUT"
            response["Access-Control-Allow-Headers"] = "Content-Type,AUTHORIZATION"

        response["Access-Control-Allow-Origin"] = "*"
        return response

    @staticmethod
    def process_exception(request, exception):
        # 发生异常所在的文件, 发生异常所在的行数

        if isinstance(exception, CustomException):
            return exception.response
        if isinstance(exception, ObjectDoesNotExist):
            return CustomException(success=False, code=22222, msg="操作对象不存在!").response

        print(exception.__traceback__.tb_frame.f_globals["__file__"], exception.__traceback__.tb_lineno)
        # return CustomException(success=False, code=99999, msg="系统繁忙!").response
